<?php

// [ 上传凭据 ]

namespace app\qiniu\lib;
use think\Config;

class UploadToken
{
    // 密钥
    private static $_accessKey;
    // 密匙
    private static $_secretKey;
    // 空间
    private static $_space;
    // 有效期
    private static $_expire;

    // 初始化
    private static function _init()
    {
        self::$_accessKey = Config::get('qiniu.accessKey');
        self::$_secretKey = Config::get('qiniu.secretKey');
        self::$_space     = Config::get('qiniu.space');
        self::$_expire    = Config::get('qiniu.expire');
    }

    public static function get()
    {
        self::_init();

        $putPolicy = [
            'scope'      => self::$_space,
            'deadline'   => time() + self::$_expire,
        ];
        $putPolicy = json_encode($putPolicy,JSON_UNESCAPED_UNICODE);
        $encodedPutPolicy = base64_encode($putPolicy);
        // 使用访问密钥（AK/SK）对生成的待签名字符串计算HMAC-SHA1签名
        $sign = hash_hmac('sha1',$encodedPutPolicy,self::$_secretKey,true);
        // 对签名进行URL安全的Base64编码
        $encodedSign = base64_encode($sign);
        // 将访问密钥（AK/SK）、encodedSign 和 encodedPutPolicy 用英文符号 : 连接起来
        $uploadToken = self::$_accessKey . ':' . $encodedSign . ':' . $encodedPutPolicy;

        return $uploadToken;
    }
}